<?php

namespace app\adminapi\middleware;

use app\common\exception\AdminException;
use app\common\service\permission\AdminService;
use think\Request;
use think\facade\Log;

class CheckPermission
{
    public function handle(Request $request, \Closure $next)
    {
        // 定义白名单路由，跳过权限验证
        $allowRoutes = [
            'sys_config:getConfig',
        ];

        // 获取当前路由信息
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $rule = $controller . '/' . $action; // 路由规则，如 menu/list
        $routeName = $request->rule()->getName() ?: ''; // 获取路由名称 user:index
        $userId = $request->userInfo['user_id'] ?? '';

        // 检查是否在白名单中
        if (in_array($rule, $allowRoutes) || in_array($routeName, $allowRoutes)) {
            return $next($request);
        }

        // 检查用户信息（依赖 JwtAuth 中间件）
        if (!isset($request->userInfo) || !isset($request->userInfo['user_id'])) {
            throw new AdminException('未认证，请先登录', 403);
        }

        // 权限验证
        if (!$this->checkPermission($rule, $routeName, $userId)) {
            throw new AdminException('未授权访问');
        }

        return $next($request);
    }

    /**
     * 检查权限
     *
     * @param $rule
     * @param $routeName
     * @param $userId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function checkPermission($rule,  $routeName,  $userId): bool
    {
        // 超级管理员（id=1）免权限验证
        if ($userId == 1) {
            Log::info('Super admin bypass permission check', ['user_id' => $userId]);
            return true;
        }

        $adminService = app()->make(AdminService::class);
        $perArr = $adminService->getPermissions($userId);

        if(in_array($routeName, $perArr)) {
            return true;
        } else {
            return false;
        }
    }
}